<template>
    <div>
        <el-form ref="ruleFormRef" :model="loginForm" :rules="rules" label-width="75px" class="demo-ruleForm"
            :size="formSize" status-icon>
            <el-form-item label="手机" prop="telephone">
                    <el-input v-model="loginForm.phoneNumber" style="width:140px" />
                    <el-button :disabled="countdown > 0" @click="openSlider">{{ countdownText }}</el-button>
                    <el-dialog v-model="showSlider" width="25%" center>
                        <SliedComponent @successEvent="getSmsVerifyCode" @startCountdown="startCountdown"></SliedComponent>
                    </el-dialog>
                </el-form-item>
                <el-form-item label="验证码" prop="verifyCode">
                    <el-input v-model="loginForm.verifyCode" style="width:183px" />
                </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    登录
                </el-button>
                <el-button @click="toRegister()">注册</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
    
<script lang="ts" setup>
import { reactive, ref, computed } from 'vue'
import { ElMessage, ElNotification, type FormInstance, type FormRules } from 'element-plus'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import api from '@/api'
import SliedComponent from '@/components/layout/SliedComponent.vue'

const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const loginForm = ref({
    phoneNumber: '',
    verifyCode: ''
})

const rules = reactive<FormRules>({
    userName: [
        {
            required: true,
            message: '用户名不能为空',
            trigger: 'change',
        },
    ],
    password: [
        {
            required: true,
            message: '密码不能为空',
            trigger: 'change',
        },
    ],
    verifyCode: [
        {
            required: true,
            message: "请输入验证码",
            trigger: "change"
        },
    ],
})

const store = useStore();
const router = useRouter();

const user = ref({
    id: '',
    userName: '',
    nickName: '',
    userType: '',
    avatar: '',
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            api.login.smsLogin(loginForm.value)
                .then(response => {
                    // 在这里可以处理提交成功后的逻辑
                    // 存储 token
                    store.dispatch('updateToken', response.data.data.token)
                    user.value.id = response.data.data.id;
                    user.value.userName = response.data.data.userName;
                    user.value.nickName = response.data.data.nickName;
                    user.value.userType = response.data.data.userType;
                    user.value.avatar = response.data.data.avatar;
                    store.dispatch('updateUserInfo', user.value);
                    store.dispatch('updateIsLoggedIn', true);
                    ElNotification({
                        title: 'Success',
                        message: response.data.msg,
                        type: 'success',
                        duration: 1500
                    })
                    if(user.value.userType === '2'){
                        router.push('/')
                    }else if(user.value.userType === '1'){
                        router.push('/admin')
                    }
                })
                .catch(error => {
                    ElNotification({
                        title: 'Error',
                        message: error.data.msg,
                        type: 'error',
                        duration: 1500
                    })
                    // 在这里可以处理提交失败后的逻辑
                });
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const toRegister = () => {
    router.push('/register')
}

const showSlider = ref(false)
const countdown = ref(0);
const countdownText = ref("获取验证码");

const openSlider = () => {
    if(loginForm.value.phoneNumber === ''){
        ElMessage.error('手机号不可为空')
        return;
    }
    showSlider.value = true
}

const startCountdown = () => {
    if (countdown.value > 0) {
        return;
      }
      countdown.value = 60;
      countdownText.value = `${countdown.value}秒`;
      const timer = setInterval(() => {
        countdown.value--;
        countdownText.value = `${countdown.value}秒`;
        if (countdown.value === 0) {
          clearInterval(timer);
          countdownText.value = '获取验证码';
        }
      }, 1000);
}

const getSmsVerifyCode = async () => {
    showSlider.value = false
    api.login.getSmsVerifyCode({ "phoneNumber": loginForm.value.phoneNumber,type:'smsLogin' })
        .then(response => {
            // 在这里可以处理提交成功后的逻辑
            ElNotification({
                title: 'Success',
                message: response.data.msg,
                type: 'success',
                duration: 1500
            })
        })
        .catch(error => {
            ElNotification({
                title: 'Error',
                message: error.data.msg,
                type: 'error',
                duration: 1500
            })
            // 在这里可以处理提交失败后的逻辑
        });
}


</script>

<style scoped></style>